package cn.xej.health.user.service.impl;

import cn.xej.health.common.constant.AuthConstant;
import cn.xej.health.common.service.RedisService;
import cn.xej.health.user.dao.ResourceDao;
import cn.xej.health.user.dao.RoleDao;
import cn.xej.health.user.dao.RoleResourceDao;
import cn.xej.health.user.entity.Resource;
import cn.xej.health.user.entity.Role;
import cn.xej.health.user.entity.RoleResource;
import cn.xej.health.user.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author xej
 */

@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceDao, Resource> implements ResourceService {
    @Autowired
    private RoleResourceDao roleResourceDao;

    @Autowired
    private RoleDao roleDao;


    @Autowired
    private RedisService redisService;

    /**
     * 初始化资源角色到redis中
     * @return
     */
    @Override
    public Map<String, List<String>> initResourceRolesMap() {
        Map<String,List<String>> resourceRolesMap = new TreeMap<>();
        List<Resource> resourceList = this.list();
        List<Role> roleList = roleDao.selectList(null);
        List<RoleResource> roleResourceList = roleResourceDao.selectList(null);
        for (Resource resource : resourceList) {
            Set<Integer> roleIds = roleResourceList.stream().filter(item -> item.getResourceid().equals(resource.getId())).map(RoleResource::getRoleid).collect(Collectors.toSet());
            List<String> roleNames = roleList.stream().filter(item -> roleIds.contains(item.getRid())).map(item -> item.getRid() + "_" + item.getRname()).collect(Collectors.toList());
            resourceRolesMap.put(resource.getUrl(),roleNames);
        }

        redisService.del(AuthConstant.RESOURCE_ROLES_MAP_KEY);
        //redis存1天
        redisService.hSetAll(AuthConstant.RESOURCE_ROLES_MAP_KEY,resourceRolesMap,3600);

        //redis存1小时
//        Boolean flag = redisService.hSetAll(AuthConstant.RESOURCE_ROLES_MAP_KEY, resourceRolesMap, 3600);

        return resourceRolesMap;
    }
}
